package com.schuxl.observer.bike;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import com.schuxl.observer.bike.dataobject.schemaTypen.sites.Sites;
import com.schuxl.observer.bike.dataobject.schemaTypen.sites.Sites.Site;
import com.schuxl.observer.bike.observer.TausendPsBikeObserver;
import com.schuxl.observer.bike.observer.WillhabenBikeObserver;




public class StartBikeObserver {

	
	public enum DOMAIN {
		WILLHABEN {public String toString() {return "willhaben.at";} },
		TAUSENDPS {public String toString() {return "1000ps.at";} },
	}
	
	//Windows
//	-Dcom.schuxl.observer.bike.contextpath=D:/Schuxl/dev/workspace/BikeObserver/
//	-Dcom.schuxl.observer.bike.config=config/config.properties
//	-Dcom.schuxl.observer.bike.log4jConfigFile=config/log4j.xml
	
	
	private static Logger LOGGER = null;
	public static Properties PROPERTIES = new Properties(); 

	
	static {
		String contextPath = System.getProperty("com.schuxl.observer.bike.contextpath");
		String configFile = System.getProperty("com.schuxl.observer.bike.config");
		String log4jConfigFile = System.getProperty("com.schuxl.observer.bike.log4jConfigFile");
		DOMConfigurator.configureAndWatch(contextPath+log4jConfigFile, 60*1000 );
		LOGGER = Logger.getLogger(StartBikeObserver.class);
		LOGGER.debug("Beginne Einlesen von config.properties");
		try {
			PROPERTIES.load(new FileInputStream(contextPath+configFile));
		} catch (Exception e) {
			LOGGER.error("Fehler beim Einlesen von config.properties. "+e);
		}
	}
	
	public static void main(String[] args) {
		try {
			LOGGER.debug("Beginne Einlesen von ObservedSites.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance("com.schuxl.observer.bike.dataobject.schemaTypen.sites");
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		    Sites sites = (Sites)unmarshaller.unmarshal(new File(StartBikeObserver.PROPERTIES.getProperty("com.schuxl.observer.bike.observedSitesFile")));
		    
		    for(Site site : sites.getSite()) {
		    	if(site.getUrl().contains(StartBikeObserver.DOMAIN.WILLHABEN.toString())) {
		    		LOGGER.debug("Starte Willhaben-BikeObserver Thread");
			    	new Thread(new WillhabenBikeObserver(site)).start();
		    	}
		    	else if(site.getUrl().contains(StartBikeObserver.DOMAIN.TAUSENDPS.toString())) {
		    		LOGGER.debug("Starte TausendPs-BikeObserver Thread");
			    	new Thread(new TausendPsBikeObserver(site)).start();
		    	}
		    }
		} catch (Exception e) {
			LOGGER.error("Fehler beim Starten! ", e);
		}
	}
	
	
	
}
